import {isURL} from './validate';

let util = {
  /** 工具 */
};

// 标题
util.title = function (title) {
  title = title || 'na admin';
  window.document.title = title;
};

/**
 * 数组中是否存在指定子数组
 * @param arr
 * @param targetArr
 * @returns {boolean}
 */
util.inOfArray = function (arr, targetArr) {
  let res = true;
  arr.forEach(item => {
    if (targetArr.indexOf(item) < 0) {
      res = false;
    }
  });
  return res;
};

/**
 * 数组中是否包含某元素
 * @param ele
 * @param targetArr
 * @returns {boolean}
 */
util.oneOf = function (ele, targetArr) {
  return targetArr.indexOf(ele) >= 0;
};

/**
 * 1
 * @param itAccess
 * @param currentAccess
 * @returns {*}
 */
util.showThisRoute = function (itAccess, currentAccess) {
  if (typeof itAccess === 'object' && Array.isArray(itAccess)) {
    return util.oneOf(currentAccess, itAccess);
  } else {
    return itAccess === currentAccess;
  }
};

/**
 * 根据名称从routers中获取路由对象（递归）
 * @param routers
 * @param name
 * @returns {*}
 */
util.getRouterObjByName = function (routers, name) {
  // debugger
  if (!name || !routers || !routers.length) {
    return null;
  }
  // debugger;
  let routerObj = null;
  for (let item of routers) {
    if (item.name === name) {
      return item;
    }
    routerObj = util.getRouterObjByName(item.children, name);
    if (routerObj) {
      return routerObj;
    }
  }
  return null;
};

/**
 * 获取title
 * @param vm
 * @param item
 * @returns {*}
 */
util.handleTitle = function (vm, item) {
  /* if (typeof item.title === 'object') {
      return vm.$t(item.title.i18n);
  } else {
      return item.title;
  } */
  return item.meta.title;
};

/**
 * 设置当前路径
 * @param vm
 * @param name
 * @returns {*[]}
 */
util.setCurrentPath = function (vm, toRoute) {
  let currentPathArr = [];
  if (toRoute.name === 'home') {
    currentPathArr = [
      {
        title: toRoute.meta.title,
        path: '',
        name: 'home'
      }];
  } else if (toRoute.name === 'ownspace') {
    currentPathArr = [
      {
        title: '首页',
        path: '',
        name: 'home'
      },
      {
        title: '个人中心',
        path: '',
        name: 'ownspace'
      }];
  } else {
    // 获取当前跳转页面的 pageOpenedList元素
    let menuList = JSON.parse(sessionStorage.getItem('menuList') || '[]');// 需要重巡设计，结合store
    let childObj;
    let currentPathObj = menuList.filter(item => {
      if (item.menuId === toRoute.meta.menuId) { // 根据menuId匹配，防止重名bug
        // parentObj = item;
        return true;
      } else {
        if (item.list && item.list.length >= 1) {
          let i = 0;
          let child = item.list;
          let len = child.length;
          while (i < len) {
            if (child[i].menuId === toRoute.meta.menuId) {
              childObj = child[i];
              return true;
            }
            i++;
          }
        }
        return false;
      }
    })[0];
    if (!childObj && currentPathObj.name === 'home') {
      currentPathArr = [
        {
          title: '首页',
          path: '',
          name: 'home'
        }
      ];
    } else if (!childObj && currentPathObj.name !== 'home') {
      currentPathArr = [
        {
          title: '首页',
          path: '/home',
          name: 'home_index'
        },
        {
          title: currentPathObj.name,
          path: '',
          name: toRoute.meta.title
        }
      ];
    } else if (childObj) {
      /* let childObj = currentPathObj.filter((child) => {
          return child.menuId === toRoute.menuId;
      })[0]; */
      currentPathArr = [
        {
          title: '首页',
          path: '/home',
          name: 'home'
        },
        {
          title: currentPathObj.name,
          path: '',
          name: currentPathObj.name
        },
        {
          title: childObj.name,
          path: '/' + childObj.url.replace('/', '-'),
          name: childObj.name
        }
      ];
    }
  }
  vm.$store.commit('setCurrentPath', currentPathArr);
  return currentPathArr;
};

/**
 * 打开新页面
 * @param vm
 * @param name
 * @param argu
 * @param query
 */
util.openNewPage = function (vm, name, argu, query) {
  let currentPageName = '';
  let pageOpenedList = vm.$store.state.app.pageOpenedList;
  let openedPageLen = pageOpenedList.length;
  let i = 0;
  let tagHasOpened = false;
  while (i < openedPageLen) {
    if (name === pageOpenedList[i].name) { // 页面已经打开
      vm.$store.commit('pageOpenedList', {
        index: i,
        argu: argu,
        query: query
      });
      tagHasOpened = true;
      break;
    }
    i++;
  }
  if (!tagHasOpened) {
    // 判断路由是预定义的还是动态的 todo
    // debugger
    let tag = util.getRouterObjByName(vm.$router, name);
    if (tag) { // 预定义路由
      tag = tag.children ? tag.children[0] : tag;
      if (argu) {
        tag.argu = argu;
      }
      if (query) {
        tag.query = query;
      }
      vm.$store.commit('increateTag', tag);
      currentPageName = name;
    } else {
      // 动态路由
      let dynamicRoutes = JSON.parse(sessionStorage.getItem('dynamicMenuRoutes') || '[]');
      let route = dynamicRoutes.filter(item => item.name === name)[0];
      if (!route) {
        console.error('无可用标签页，刷新重试');
        return;
      } else {
        let tag = {
          menuId: route.meta.menuId || route.name,
          name: route.name,
          title: route.meta.title,
          type: isURL(route.meta.iframeUrl) ? 'iframe' : 'module',
          iframeUrl: route.meta.iframeUrl || ''
        };
        if (argu) {
          tag.argu = argu;
        }
        vm.$store.commit('increateTag', tag);
        currentPageName = route.meta.title;
      }
    }
  }
  vm.$store.commit('setCurrentPageName', currentPageName);
};

util.toDefaultPage = function (routers, name, route, next) {
  let len = routers.length;
  let i = 0;
  let notHandle = true;
  while (i < len) {
    if (routers[i].name === name && routers[i].children && routers[i].redirect === undefined) {
      route.replace({
        name: routers[i].children[0].name
      });
      notHandle = false;
      next();
      break;
    }
    i++;
  }
  if (notHandle) {
    next();
  }
};

/**
 * 获取UUID
 * @returns {string}
 */
util.getUUID = function () {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
    return (c === 'x' ? (Math.random() * 16 | 0) : ('r&0x3' | '0x8')).toString(16)
  })
};

/**
 * 是否有权限
 * @param key
 * @returns {boolean}
 */
util.isAuth = function (key) {
  return JSON.parse(sessionStorage.getItem('permissions') || '[]').indexOf(key) !== -1 || false;
};

util.formatDate = function (date) {
  const y = date.getFullYear();
  let m = date.getMonth() + 1;
  m = m < 10 ? '0' + m : m;
  let d = date.getDate();
  d = d < 10 ? ('0' + d) : d;
  return y + '-' + m + '-' + d;
};
/**
 * 文件下载
 * @param blob 二进制输出流
 * @param fileName 文件名（含后缀，配合axios使用）
 */
util.downloadFile = function (blob, fileName) {
  if (window.navigator.msSaveOrOpenBlob) {
    navigator.msSaveBlob(blob, fileName);
  } else {
    let link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    link.download = fileName;
    link.click();
    window.URL.revokeObjectURL(link.href);
  }
};

export default util;
